#include<stdio.h>
#include<unistd.h>
 #include <sys/types.h>
 #include <sys/stat.h>
 #include <fcntl.h>
 #include<string>
 #include <sys/wait.h>
#include <sys/types.h>
#include<string.h>

#define BUFFER_SIZE 1024

int main()
{
    /*管道创建*/
    int pipeFd[2]={0};
    int ret=pipe(pipeFd);
    if(ret==-1)
    {
        perror("pipe error:");
        _exit(-1);
        
    }
    /*创建子进程*/
    pid_t pid=fork();
    if(pid<0)
    {
        perror("fork error:");
        exit(-1);
    }
    else if (pid==0)
    {
        /*把写端关闭*/
        close(pipeFd[1]);


        /*子进程*/
        /*从管道里读*/
        sleep(10);
        char buffer[1024]={0};
        /*read是一个“阻塞函数*/
        
        int readBytes=read(pipeFd[0],buffer,sizeof(buffer));

        printf("child %d,%s",readBytes,buffer);
    }
    else
    {   /*把读端关闭*/
        close(pipeFd[0]);


        /*父进程*/
        /*父进程负责写*/
    while(1)
    {

        usleep(100);
        char *buffer[BUFFER_SIZE];
        memset(buffer,'a',sizeof(buffer));
        int writeBytes= write(pipeFd[1],(const void*)buffer,strlen(buffer));
        printf("writeBytes=%d,\tbuffer=%s",writeBytes,buffer);

    }
        /*向管道里面写数据*/
        // int writeBytes= write(pipeFd[1],(const void*)buffer,strlen(buffer));
        // char buf[BUFFER_SIZE];
        // int readBytes=read(pipeFd[0],buf,sizeof(buf));
        // printf("parent readBytes=%d,\tbuf=%s\n",readBytes,buf);
        /*阻塞回收等待子进程*/
        wait(NULL);
        printf("recycle success.\n");
    }
    




    return 0;
}